package com.wen.springbootorderserver.service;

import com.wen.springbootorderserver.dao.OrderDatabase;
import com.wen.springbootorderserver.pojo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderService {

    @Autowired
    private OrderDatabase orderDatabase;

    //创建订单
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(Orders order)throws Exception{

        //添加订单
        orderDatabase.saveOrder(order);

        //通过http接口发送信息到运单系统
        String dispatch = dispatch(order.getOrderId());
        if(!dispatch.equals("success")){
            throw new Exception("调用运单接口失败");
        }

    }


    //模拟发送请求
    private String dispatch(String orderId){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 连接时间大于3s，超时
        factory.setConnectTimeout(3000);
        // 处理时间>3s,超时
        factory.setReadTimeout(2000);

        String http = "http://localhost:9000/dispatch/order?orderId="+orderId;
        RestTemplate restTemplate = new RestTemplate(factory);
        String rest = restTemplate.getForObject(http, String.class);
        return rest;
    }



}
